<template>
	<!-- 系统目录 西成药品 -->
	<div class="MedicenCata">
		<!--  描述  -->
		<div class="header">
			<div class="header-icon">
				<i class="el-icon-ggml"
					style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;background-color: #409EFF;color: #fff;"></i>
				<span style="font-size: 12px;font-weight:400;margin-left: 12px;">科室档案</span>
			</div>
		</div>
		<!-- main -->
		<div class="main">
			<!-- left -->
			<div class="main-left" :style="{ height: viewportHeight + 'px' }">
				<!-- tree -->
				<el-tree 
				:data="elTree" 
				:props="defaultProps"
				node-key="label"
				:default-expanded-keys="['全部']"
				accordion 
				@node-click="handleNodeClick"
				class="custom-tree"
				>
					<span class="custom-tree-node" slot-scope="{ node, data }" style="font-size: 12px;">
						<span :name="node.label">
							<i v-if="!data.children"
							:class="node.expanded ? 'el-icon-openFile' : 'el-icon-closeFiles'"></i>
							<i v-else class="el-icon-openFile"></i>{{ node.label }}
						</span>
					</span>
				</el-tree>
			</div>
			<!-- right -->
			<div class="main-right" ref="mainRight">
				<!-- tit -->
				<div class="main-icon">
					<div class="main-icon-a">
						<i :class="iconComes" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #5a5a5a;color: #fff;"></i>
						<span style="font-size: 12px;font-weight:bold;margin-left: 12px;color: #606266;">{{ CatalogueName }}</span>
					</div>
					<!-- btn1 -->
					<div class="main-icon-b">
						<span style="font-size: 12px;color: #606266;font-weight: bold;">状态：</span>
						<el-dropdown @command="handleCommand" trigger="click">
							<span class="el-dropdown-link">{{ DropDownedName }}<i class="el-icon-down"></i></span>
							<el-dropdown-menu slot="dropdown">
							  <el-dropdown-item command="a">可用</el-dropdown-item>
							  <el-dropdown-item command="b">禁用</el-dropdown-item>
							  <el-dropdown-item command="c" divided>全部</el-dropdown-item>
							</el-dropdown-menu>
					    </el-dropdown>
					</div>
					<!-- btn2 -->
					<div class="main-icon-c">
						<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
						<el-input size="mini" placeholder="编码、名称、拼音简码" suffix-icon="el-icon-key" v-model="searchValue"></el-input>
					</div>
					<!-- btn3 -->
					<div class="main-icon-c">
						<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(i)">{{ v.title }}</el-button>
					</div>
				</div>
				<!-- add data -->
				<!-- table -->
				<div class="table">
					<el-table :data="tableData" border @row-dblclick="handledbRow" :style="{ width: tableWidth + 'px' }">
						<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
						<!-- fixed -->
						<el-table-column fixed="left" label="行号" type="index"></el-table-column>
						<!-- edit -->
						<el-table-column fixed="right" label="操作" width="160">
						      <template slot-scope="scope">
								  <div class="editbox" style="text-align: center;">
									<el-button type="primary" @click="handleClickEdit(scope.row)" size="mini">编辑</el-button>
									<el-button type="danger" @click="handleDelete(scope.row.id)" size="mini">删除</el-button>
								  </div>
						      </template>
						</el-table-column>
					</el-table>
				</div>
				<!-- 分页 -->
				<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageNum"
				:page-sizes="[5, 10, 20]"
				:page-size="pageSize"
				:total="totalSize"
				layout="total, sizes, prev, pager, next, jumper"
				background
				>
				</el-pagination>
			</div>
		</div>
		<!-- feet -->
		

	</div>
</template>/

<script>
	// selfs / js
	// 行政区域
	import ksDangan from "../../../external/ksDangan.js";
	// import MedicenCata from '../../external/MedicenCata.js'
	// 接口
	export default {
		components: {
			// MedicenCata
			// City
		},
		data() {
			return {
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				// str
				tableWidth:'', //右侧表格动态宽度
				viewportHeight: 0, // 用于存储视口高度
				watch:'查看',
				searchValue:'',
				toCodeNum:'0000',//拼接自增 导零
				iconHandleClick:'el-icon-plus',
				CatalogueName:'科室档案',
				DropDownedName:'可用',
				typeValue:'',
				YNuseVaule:'可用',
				nowDateTimeValue:'',
				iconComes:'el-icon-ggml',
				operatingTime:'',
				// boolean
				disabled:true,
				noEidt:true,
				formdisabled:true,
				loading:false,
				dialogVisible:false,	//此乃查看/编辑控制
				addDialogVisible:false, //此乃新增控制
				// number
				dataIndex: 0,
				CodeNumber:0,
				pageNum: 1, //当前页currentPage
				pageSize: 8,
				totalSize: 10, //总条数
				/* obj */
				// 新增
				addForm: {
				  	code: "",
				  	gradeCode: "001",
				  	label: "",
				  	operatingTime: "",
				  	operator: "",
				  	remark: "",
				  	status: "",
				},
				// 编辑 / 查看
				form: {
				  label: '',
				  code: '',
				  status:'',
				  textSpell:'',
				  nz:'',
				  num: '',
				  opdate:'',
				  opeater:'',
				  remark:'',
				},
				// 新增验证规则
				addrules:{
				    label: [
				      { required: true, message: "名称不能为空！", trigger: "blur" },
				      { min: 2, max: 8, message: "长度在2到8个字符", trigger: "blur" },
				    ],
				    //有效状态
				    status:[
				       { required: true, message: "请选择一个有效状态！", trigger: "blur" },
				    ],
					//操作人
					operator:[
					   { required: true, message: "不能为空！", trigger: "blur" },
					]
				},
				// arr
				data: [],
				oop:[],
				userInfo: [],
				watchData: [],
				YNuse:[{ id:1,label:'可用',value:'1'},{ id:2,label:'禁用',value:'2'}],
				drugTypeOptions:[{ id:1,label:'毒麻类',value:'毒麻类'},{ id:2,label:'精神类',value:'精神类'}],
				// title右侧按钮
				headerBtn:[
				 { refesh:"refesh", title:"刷新", type:"", icon:"el-icon-refresh" },
				 { senior:"senior", title:"高级", type:"", icon:"" },
				 { add:"add", title:"新增", type:"warning" },
				],
				// title右侧按钮
				tableRows:[
					{ name:"系统序号", prop:"num", type:"" },{ name:"编码", prop:"code", nz:"nz" },{ name:"名称", prop:"label", type:"" },
					{ name:"科室专业", prop:"major", type:""},{ name:"负责人", prop:"operator", type:"" },{ name:"负责人电话", prop:"tel", type:"" },
					{ name:"物理位置", prop:"local", nz:"nz" },{ name:"院区", prop:"yq", type:"" },{ name:"隶属机构", prop:"jg", type:"" },
					{ name:"有效状态", prop:"status", type:"" },{ name:"主索引ID", prop:"id", type:"" },{ name:"操作时间", prop:"operatingTime", type:"" },
					{ name:"操作人", prop:"operator", type:"" },{ name:"备注", prop:"remake", type:"" },{ name:"医学类型i", prop:"type", type:"" },
					{ name:"科室类型i", prop:"type1", type:"" },{ name:"返诊期限", prop:"return", type:"" },
				],
				elTree:[
					{ label: '全部', path:'', title:'', icon:'el-icon-news',children:[]},
				],
				tableData: [
					{ id: '001', num:'399', code:'3259',jg:'九阵科技', label: '药剂科', status: '可用',yq:'水富市人民医院',local:'', major: '其他业务科室',operatingTime:'2024-12-05 14：36：48',operator:'超级管理员',type:'0',type1:'6',return:'0' },
					{ id: '002', num:'401', code:'3266',jg:'九阵科技', label: '药剂科', status: '可用',yq:'水富市人民医院',local:'', major: '其他业务科室',operatingTime:'2024-12-05 14：36：48',operator:'超级管理员',type:'0',type1:'6',return:'0' },
				],
				 pickerOptions: {
				  shortcuts: [{
					text: '今天',
					onClick(picker) {
					  picker.$emit('pick', new Date());
					}
				  }, {
					text: '昨天',
					onClick(picker) {
					  const date = new Date();
					  date.setTime(date.getTime() - 3600 * 1000 * 24);
					  picker.$emit('pick', date);
					}
				  }, {
					text: '一周前',
					onClick(picker) {
					  const date = new Date();
					  date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
					  picker.$emit('pick', date);
					}
				  }]
				},
			};
		},
		computed: {
		    // 格式化数字，确保4个0后的数字自增时不会出现前导零
		    formattedNumber() {
				return '00000' + this.toCodeNum.toString().slice(1);
		    },
		  },
		mounted() {
			//获取动态盒子宽度，实时赋值给右侧
			this.$nextTick(()=>{
				this.tableWidth = this.$refs.mainRight.offsetWidth - 828;
				// console.log(this.tableWidth,'888888');
			})

			// 模拟信息
			this.oop = ksDangan.map(function(v) {
				return v
			})
			// 赋值给Options
			this.elTree[0].children.push(...this.oop)
			this.updateViewportHeight(); // 初始化视口高度
			window.addEventListener('resize', this.updateViewportHeight); // 监听窗口大小变化
		},
		beforeDestroy() {
		    window.removeEventListener('resize', this.updateViewportHeight); // 移除监听
		},
		methods: {
			/*
				about tree
			*/
			handleNodeClick(data,e) {
				// this.CatalogueName = data.title
				// this.iconComes = 'el-icon-' + 'jldw'
				// // console.log(this.iconComes);
				// this.loadData();
				// // console.log(this.makePy(data.label));
				// // console.log( data.label);
				// // if(data != ''){
				// // 	this.treeMenu();
				// // }
			},

			// 窗口高度
			updateViewportHeight() {
			  this.viewportHeight = window.innerHeight - 145; // 获取并更新视口高度
			  // console.log(this.viewportHeight);
			},
			/*
				about table
			*/
		   
		   // 数据源 
		    loadData(){
			
			
		   },
		   // col 里面包含了表头字段和名称，list 是表格数据
		       columnWidth(col, list) {
		         let prop = col.prop,lab = col.lab;
		         let width = 40; // 设定一个最小值
		         let maxlenStr = ""; // 最长字符串
		         for (let info of list) {
		           if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		         }
		         width = Math.max(width, len(lab), len(maxlenStr));
		         // 表格自带的内边距(20px) 自调
		         return width + 8; // 这里加了 18px
		         function len(str) {
		           // 实际分配长度可根据需要自行调整
		           let length = 8;
		           for (const char of str + "") {
		             // 英文小写字符 8px
		             if ("a" <= char && char <= "z") length += 8;
		             // 英文大写字符 8px
		             else if ("A" <= char && char <= "Z") length += 8;
		             // 中文字符 28px
		             else if (char >= "\u4e00" && char <= "\u9fa5") length += 18;
		             // 其他 8px
		             else length += 12;
		           }
		           return length;
		         }
		       },
			// see table
			handleDelete(id){
				this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					}).then(async () => {
						let res = await deleteByPoison(id);
						let { code, message } = res;
						if (res.code === 200) {
							this.$message({
								type: "success",
								message: message,
							});
							this.loadData(); //更新数据驱动
						} else {
							this.$message.error(message);
						}
					})
					.catch(() => {
						this.$message({
							type: "fail",
							message: '失败',
						});
					});
			},
			// edit table
			handleClickEdit(val){
				this.watch = '编辑';
				this.form = val; this.dialogVisible = true;this.noEidt = true,
				this.formdisabled = false;
			},
			// 编辑保存
			async saveEditData(){
				console.log(this.form);
				let rs = await updatePoisonAnesthesia(this.form);
				let { code,message } = rs;
				if (code === 200) {
					this.$message({
						type: 'success',
						message: '修改成功！',
					});
					this.loadData(); //更新驱动
					this.dialogVisible = false;
				} else {
					this.$message.error('失败！')
				}
			},
			//新增保存
			addNewData(){
				// let res = await addPoisonAnesthesia(this.addForm)
				console.log(this.addForm);
				//触发验证表单
				this.$refs.addForm.validate(async(valid) => {
				  if(valid){
				    //验证通过
				    // console.log('submit');
				    let res = await addPoisonAnesthesia(this.addForm)
				    console.log(res);
					if (res.code === 200){
					this.$message({
						message:res.message,
						type:"success"
					});
					this.loadData(); //更新数据驱动
					}else{
					  //验证失败
					  console.log('失败');
					}
				}
				});
			},
			// input 
			inputLabel(){
				this.addForm.code = this.makePy(this.addForm.label).toLocaleUpperCase().slice(0,1) + this.formattedNumber + this.CodeNumber;//编码
				this.addForm.textSpell = this.makePy(this.addForm.label).toLocaleUpperCase();//拼音简码
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
				  .then(_ => {
					this.formdisabled = true;
					done();
				  })
				  .catch(_ => {
					this.formdisabled = this.formdisabled;
				  });
			},
			// db events
			handledbRow(row, column, event){
				if(row){ this.form = row; this.dialogVisible = true } else { console.log('fail'); }
				// console.log(this.form);
				this.formdisabled = true
				this.form.textSpell = this.makePy(this.form.label).toLocaleUpperCase()
				// console.log(this.form.textSpell);
			},

			// 步骤
			handClick(i) {
				// i event
				switch (i) {
					case 0:
						// 处理索引0的逻辑
						this.loading = true;
						if(this.searchValue == ''){
							setTimeout(() => {
								this.$message.error('关键字不能为空！');
								this.loading = false;		
							}, 1500)
						}else{
							this.$confirm('敬请期待')
							.then(_ => {})
							.catch(_ => {});
						}
						break;
					case 1:
						// 处理索引1的逻辑
						this.$confirm('敬请期待')
							.then(_ => {})
							.catch(_ => {});
						break;
					case 2:
						// 处理索引2的逻辑 => 新增
						this.addDialogVisible = true
						break;
				}
			},
			handleCommand(command) {
			  // console.log(command);
			  // 根据 command 值执行相应的逻辑
			  switch (command) {
				case 'a':
				  // 处理a的逻辑
				  console.log('执行A逻辑');
				  this.DropDownedName = '可用'
				  break;
				case 'b':
				  // 处理b的逻辑
				  console.log('执行B逻辑');
				  this.DropDownedName = '禁用'
				  break;
				case 'c':
				  // 处理b的逻辑
				  this.DropDownedName = '全部'
				  break;
				// ... 其他 case
			  }
			},
			//分页
			//每页条数改变触发
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.pageNum = val;
			},
			//当前条数改变触发
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.pageNum = val;
			},
			// 系统当前日期时间
			nowDateTime(){
				const now = new Date(); //创建时间日期对象
				const year = now.getFullYear(); //年
				const month = now.getMonth() + 1; //月份是从0开始的
				const day = now.getDate(); //日
				const hours = now.getHours(); //小时
				const minutes = now.getMinutes(); //分钟
				const seconds = now.getSeconds(); //秒
				const currentDate = `${year}-${month}-${day}`.replace(/-/g, '') //替换操作
				this.nowDateTimeValue = `${year}-${month}-${day}` + ` ` + `${hours}:${minutes}:${seconds}`
				// this.datetimesinglend = 
				// 将字符串转换为Date对象
				// console.log(this.nowDateTimeValue);
			}
			
		}
	}
</script>

<style lang="less" scoped>
	// 穿透
	/deep/ .el-input.is-disabled .el-input__inner{
		color: #87898f;
	}
	/deep/ .el-textarea.is-disabled .el-textarea__inner{
		color: #87898f;
	}
	/deep/ .el-icon-arrow-left:before {
	    content: "\e67d";
	    font-size: 18px;
	}
	/deep/ .el-dropdown-menu__item{
		font-size: 12px;
	}
	/deep/ .el-pagination{
		padding: 0 14px;
	}
	/deep/ .el-dialog__body{
		padding: 30px;
	}
	/deep/ .el-descriptions{
		font-size: 12px !important;
	}
	/deep/ .el-descriptions-item__container{
		display: flex !important;
		// align-items: center !important;
		padding-top: 12px !important;
	}
	/deep/ .el-descriptions-item__label:not(.is-bordered-label){
		padding-left: 0;
		width: 66px;
		display: flex;
		justify-content: right;
	}
	/deep/ .el-color-picker__icon, .el-input, .el-textarea{
		width: 100%;
	}
	/deep/ .el-pagination{
		padding: 8px;
	}
	// content
	.MedicenCata {
		height: 100%;
		width: 100%;
		// header
		.header {
			display: flex;
			flex-direction: row;
			align-items: center;
			height: 40px;
			background-color: #efefef;
			padding: 4px;
			// justify-content: space-evenly;
			// icon
			.header-icon {
				display: flex;
				align-items: center;
			}

		}

		// main
		.main {
			width: 100%;
			display: flex;
			justify-content: space-between;
			// height: 473px; /* 设置父容器的高度 */
			overflow-y: auto; /* 当内容超出容器高度时显示垂直滚动条 */
			// left
			.main-left {
				.custom-tree {
				  max-height: 100%; /* 设置树形菜单的最大高度为父容器的100% */
				  overflow-y: auto; /* 当内容超出设定高度时显示滚动条 */
				}
				/deep/ .el-tree-node__content {
					// height: 40px;
					// padding-right: 8px !important;
				}
				/deep/ .el-tree-node__label{
					font-size: 12px;
				}
				flex: 1;
				width: 168px;
				height: 100%;
			}

			// right
			.main-right {
				flex: 4;
				height: 100%;
				// alert
				.addmessagesBox{
					.tabs{
						/deep/ .el-select>.el-input{
							width: 172px;
						}
						/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
							width: 172px;
						}
						/deep/ .el-form-item__content{
							display: flex;
							
							span{
								font-size: 12px;
							}
						}
						.oneLine{
							width: 524px;
							// background-color: indianred;
						}
					}
					/deep/ .el-dialog__title{
						font-size: 12px;
					}
					/deep/ .el-table{
						font-size: 12px;
					}
				}
				// icon
				.main-icon {
					display: flex;
					align-items: center;
					padding: 12px;
					line-height: 40px;
					.main-icon-a{
						// width: 240px;
						// background-color: #00557f;
					}
					.main-icon-b{
						margin-left: 28px;
						/deep/ .el-dropdown{
							font-size: 12px;
							cursor: pointer;
						}
						/deep/ .el-dropdown:hover {
							font-weight: bold;
							color: #66b1ff;
						}
						/deep/ .el-icon--right{
							// background-color: #66b1ff;
						}
						/deep/ .el-popper[x-placement^=bottom]{
							margin-top: 0;
						}
					}
					// c
					.main-icon-c{
						display: flex;
						margin-left: 28px;
						/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
							width: 80%;
						}
					}
				}
				// table
				/deep/ .el-table .cell{
					font-size: 12px;
					text-align: center;
				}
				
				/deep/ .el-table td.el-table__cell div :first-child{
					text-align: center;
				}
				/deep/ .el-table td.el-table__cell div{
					text-align: left;
					overflow: hidden;
					white-space: normal;
					word-break: break-all;
				}
				
				.table{
					
				}
			}
		}

		// feet
		.feet {

			// alert
			.messagesBox{
				.tabs{
					
					/deep/ .el-form-item__content{
						display: flex;
						
						span{
							font-size: 12px;
						}
					}
					.oneLine{
						width: 524px;
						// background-color: indianred;
					}
				}
				/deep/ .el-dialog__title{
					font-size: 12px;
				}
				/deep/ .el-table{
					font-size: 12px;
				}
			}
		}

	}
</style>